<?php
declare (strict_types=1);

namespace app\middleware;

use app\APIResponse;
use app\utils\JwtUtils;

class Auth {
    private static string $loginUrl = "/system/login";

    /**
     * 处理请求
     * @param \think\Request $request
     * @param \Closure $next
     * @return Response|\think\Response
     */
    public function handle($request, \Closure $next) {
        // 获取不带参数的URL路径
        $path = $request->pathinfo();
        // 判断是否为登录路径
        if ($path == trim(self::$loginUrl, '/')) {
            return $next($request);
        }

        // 验证token
        if (!JwtUtils::validateRequest($request)) {
            return APIResponse::error("请先登录！", 401);
        }

        // 获取并设置用户ID
        $uid = JwtUtils::getUidFromRequest($request);
        if ($uid === null) {
            return APIResponse::error("token验证失败", 401);
        }

        return $next($request);
    }
}
